import { bomApi, EBomSource } from '@/api';
import { getMarkedDesigns } from '@/api/store/marked-design';
import { Modal } from '@/components/Modal';
import { useBoolean } from 'ahooks';
import { Button, Form, Input, Table, Typography } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { isNil, negate } from 'lodash-es';
import React, { useState } from 'react';

const log = console.log.bind(null, '[SelectDesign]');

export interface IDesignData {
  designId: string;
}

interface Props {
  title: string;
  onConfirm(data: IDesignData): void;
}
const DesignModalBtn: React.FC<Props> = (props) => {
  const { title } = props;
  const [modalOpen, { setTrue: showModal, setFalse: closeModal }] =
    useBoolean(false);

  const handleOk = async () => {
    const fieldsValue = form.getFieldsValue();
    // log({ fieldsValue });
    const { designId } = fieldsValue;
    log({ designId });
    props.onConfirm({ designId });
    closeModal();
  };

  const [form] = Form.useForm<{ designId: string }>();

  interface Design {
    designId: string;
    designName: string;
  }
  const [dataSource, setDataSource] = useState<Design[]>();
  const columns: ColumnsType<Design> = [
    {
      title: '方案ID',
      dataIndex: 'designId',
    },
    {
      title: '方案名称',
      dataIndex: 'designName',
    },
    {
      title: '操作',
      dataIndex: 'designId',
      render(designId) {
        return (
          <Button
            type="link"
            size="small"
            onClick={() => {
              props.onConfirm({ designId });
              closeModal();
            }}
          >
            回归
          </Button>
        );
      },
    },
  ];
  async function onOpen() {
    const designIds = await getMarkedDesigns();
    const designs = await bomApi.getDesignList({ designIds });
    log({ designs });
    setDataSource(designs);
  }

  return (
    <>
      <Button
        type="primary"
        onClick={() => {
          showModal();
          onOpen();
        }}
      >
        {title}
      </Button>
      <Modal
        title={title}
        open={modalOpen}
        onOk={handleOk}
        onCancel={closeModal}
        fullscreen={{ default: true }}
      >
        <Typography.Title level={5}>
          请输入方案ID，用以导入方案下的板件
        </Typography.Title>
        <Form form={form} initialValues={{ source: EBomSource.ordered }}>
          <Form.Item label="方案ID" name="designId">
            <Input />
          </Form.Item>
        </Form>
        <Typography.Title level={5}>已标记基准数据的方案</Typography.Title>
        <Table columns={columns} dataSource={dataSource} />
      </Modal>
    </>
  );
};

export default DesignModalBtn;
